package com.ricchieri.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.dao.interf.ITripDao;
import com.ricchieri.filter.TripFilter;
import com.ricchieri.model.Trip;
import com.ricchieri.util.StringUtils;

public class TripDao extends GenericDao implements ITripDao {
	private static final long serialVersionUID = 9039754826744446962L;

	@Override
	@SuppressWarnings("unchecked")
	public List<Trip> getAllTrip(TripFilter tripFilter) {
		Criteria criteria = criteriaAllTrip(tripFilter);
		
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Trip> getAllTripPaginatedByFilter(
			TripFilter tripFilter, int startRecord) {
		Criteria criteria = criteriaAllTrip(tripFilter);
		criteria.setMaxResults(BusinessSettings.ROW_MAX_RESULT);
		criteria.setFirstResult(startRecord);
		
		return criteria.list();
	}

	@Override
	public int getAllTripCountByFilter(TripFilter tripFilter) {
		Criteria criteria = criteriaAllTrip(tripFilter);
		Long result = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
		return new Integer(result.intValue());
	}
	
	@Override
	public Trip getTripById(TripFilter tripFilter) {
		Criteria criteria = criteriaAllTrip(tripFilter);
		
		return (Trip) criteria.list().get(0);
	}
		
	private Criteria criteriaAllTrip(TripFilter trip) {
		Criteria criteria = super.criteriaAllBasic(trip, Trip.class);
		
		if(StringUtils.isNotEmpty(trip.getOrigin())) {
			criteria.createAlias(getTableName().concat(".placeOrigin"), "origin");
			criteria.add(Restrictions.eq("origin.id", trip.getOriginId()));
		}
		
		if(StringUtils.isNotEmpty(trip.getDestiny())) {
			criteria.createAlias(getTableName().concat(".placeDestiny"), "destiny");
			criteria.add(Restrictions.eq("destiny.id", trip.getDestinyId()));
		}
		
		return criteria;
	}

	@Override
	protected String getTableName() {
		return "trip";
	}	
}
